package com.ws.shop.util;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.MemoryCacheImageInputStream;

import org.apache.commons.io.IOUtils;

public class ImageHelper {
	public static boolean validateImageType(byte[] mapObj) {
		boolean ret = false;
		ByteArrayInputStream bais = null;
		MemoryCacheImageInputStream mcis = null;
		try {
			bais = new ByteArrayInputStream(mapObj);
			mcis = new MemoryCacheImageInputStream(bais);
			Iterator<ImageReader> itr = ImageIO.getImageReaders(mcis);
			while (itr.hasNext()) {
				ImageReader reader = (ImageReader) itr.next();
				String imageName = reader.getClass().getSimpleName();
				if (imageName != null
						&& ("GIFImageReader".equals(imageName) || "JPEGImageReader".equals(imageName)
								|| "PNGImageReader".equals(imageName) || "BMPImageReader".equals(imageName))) {
					ret = true;
				}
			}
		} finally {// 关闭流
			try {
				if (mcis != null) {
					mcis.close();
				}
				if(bais != null){
                    bais.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return ret;
	}

	public static boolean validateImageType(InputStream input) {
		try {
			return validateImageType(IOUtils.toByteArray(input));
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}
}
